<template>
  <div class="station-container">
    <!-- toast -->
    <toast :show.sync="toastShow" position="center" :delay="-1">数据加载中...</toast>

    <section class="station-search">
      <div class="PK-searchInput__wrap">
        <i class="PK-searchInput__icon">
          <em class="icon-search" style="vertical-align: -2px"></em>
        </i>
        <input class="PK-searchInput__entity bd_none" type="text" placeholder="搜索"
               maxlength="32" autofocus v-model="tripForm.startStation"
               @keyup="searchStation(tripForm.startStation)"
        >
      </div>
    </section>
    <section class="station-result">
      <tab>
        <!-- 附近路线与站点 -->
        <tabs title="附近路线与站点">
          <!-- 默认展示的地理位置提示 -->
          <ul class="nearly-station-list" v-if="showNearlyStation">
            <li class="nearly-station-item" v-for="station in nearlyBusStationAndLine"
                @click="nearlyPlaceClickHandler(station)">
              <em class="icon-little-zhanpai" v-if="station.type === 'busStation'"
                  style="vertical-align: -2px; color: #CECECE;"></em>
              <em class="icon-gongjiao" v-else
                  style="vertical-align: -2px; color: #CECECE;"></em>

              <span v-text="station.name" style="padding-left: 4px;"></span>
            </li>
          </ul>

          <!-- 站点地理自动填充 -->
          <ul class="bus-info-list" v-if="!showNearlyStation">
            <li class="bus-info-item" v-for="station in busStationAutoComplete"
                @click="busStationClickHandler(station)"
            >
              <i class="bus-info-icon">
                <!-- 公交线路没有 location -->
                <em class="icon-little-zhanpai" v-if="station.location"
                    style="vertical-align: -2px; color: #CECECE;"></em>
                <em class="icon-gongjiao" v-else
                    style="vertical-align: -2px; color: #CECECE;"></em>
              </i>
              <section class="bus-info-right">
                <h5 class="bus-station-name">
                  {{station.name | keywordHighlight tripForm.startStation}}
                </h5>
                <ul class="bus-info-stations" v-if="station.address">
                  <li class="bus-info-stations-item"
                      v-for="line in station.address.split(';')"
                      v-text="line"></li>
                </ul>
              </section>
            </li>
          </ul>
        </tabs>

        <!-- 历史记录 -->
        <tabs title="历史搜索记录">
          <ul class="nearly-station-list">
            <li class="nearly-station-item">暂无历史记录...</li>
          </ul>
        </tabs>
      </tab>
    </section>
  </div>
</template>

<script>
  import { toast } from '@/components/toast'
  import { tab, tabs } from '@/components/tabs/index'
  import Geolocation from '@/api/Geolocation';
  import {mapGetters,mapActions,mapState} from 'vuex'
  // import { setStationInfo } from 'VUEX/actions/tripStation';

  export default {
    data() {
      return {
        LineSearch: null,                                 // 高德 LineSearch 对象
        PlaceSearch: null,                                // 高德 PlaceSearch 对象
        Autocomplete: null,                               // 高德 Autocomplete 对象

        tripForm: {
          stationType: 'startStation',                        // 起点还是结束
          type: 'inwork',                                     // 设置上班还是下班的行程
          startStationName: '',                               // 起始站点
          startStationGeo: null,                              // 起始站点地理位置信息
          endStationName: '',                                 // 结束站点
          endStationGeo: null                                 // 结束站点地理位置信息
        },

        toastShow: true,                                  // 提示显示
        showNearlyStation: true,                          // 是否显示附近公交站线路
        nearlyBusStationAndLine: [],                      // 附近公交线路和公交站
        busStationAutoComplete: []                        // 输入自动填充
      }
    },

    // vuex: {
    //   actions: {
    //     setStationInfo
    //   }
    // },
    computed: {
      ...mapState([
        'position',
      ]),
      init(){
        this.$store.dispatch('getCurrentPosition', 'AMap')
        let a = this.position;
        // Geolocation.init();
        // Geolocation.getInstance().addWatch(this.positionChangeHandler, this);
        this.positionChangeHandler();

        // 获取 city code 初始化相关高德服务.
        this.PlaceSearch = new window.AMap.PlaceSearch({
          type: '交通设施服务', city: this.position.citycode, citylimit: true, pageSize: 20
        });
        // 初始化高德自动填充服务
        this.Autocomplete = new window.AMap.Autocomplete({
          city: this.position.citycode, citylimit: true, datatype: 'all'
        });

        // 搜索附近的公交站点和公交线路
        this.searchNearlyBusStationAndBusLine(this.position.position);
      },
    },
    mounted(){
      debugger
      // this.$store.dispatch('getCurrentPosition', 'AMap')
      // let a = this.position;
      // // Geolocation.init();
      // // Geolocation.getInstance().addWatch(this.positionChangeHandler, this);
      // this.positionChangeHandler();

      // // 获取 city code 初始化相关高德服务.
      // this.PlaceSearch = new window.AMap.PlaceSearch({
      //   type: '交通设施服务', city: this.position.citycode, citylimit: true, pageSize: 20
      // });
      // // 初始化高德自动填充服务
      // this.Autocomplete = new window.AMap.Autocomplete({
      //   city: this.position.citycode, citylimit: true, datatype: 'all'
      // });

      // // 搜索附近的公交站点和公交线路
      // this.searchNearlyBusStationAndBusLine(this.position.position);
    },

    filters: {
      /**
       * @desc 站点搜索关键字高亮过滤器
       * @param keyword {String} 公交站点名称
       * @param vmKeyword {String} 目前正在输入的站点名称
       * @return {String} 加入高亮标签的 html
       */
      keywordHighlight (keyword, vmKeyword) {
        return String.prototype.replace.call(keyword
          , vmKeyword
          ,`<span class="bus-station-name-hit">${vmKeyword}</span>`);
      }
    },

    methods: {
      /**
       * @desc 地理位置变更事件处理函数
       * @param geo {Object} 地理位置信息  {addressComponent: {citycode}, position}
       */
      positionChangeHandler ({position}) {
        this.searchNearlyBusStationAndBusLine(position);
      },

      /**
       * @desc 搜索附近的公交站点和公交线路
       * @param position {Object} 地理位置.
       */
      searchNearlyBusStationAndBusLine (position) {
        debugger;
        if (!position) { return; }
        //   	throw new TypeError('mmp position parameter is null.');

        let nearlyBusLine = [];
        let pois = this.position.positioninfo.pois;
        nearlyBusLine = L.uniq(pois.map(({address}) => address)
            .join('').split(';')).map(name => { return {name: name} });

          this.nearlyBusStationAndLine = pois.concat(nearlyBusLine)
            .map(({name, location = null, type = 'busLine', id}) => {
              return {
                id: id,
                name: name,
                location: location,
                type: type === 'busLine' ? type : 'busStation'
              }
            });

          this.toastShow = false;


        // this.PlaceSearch.searchNearBy('公交线路', position, 400, (status, {poiList: {pois}}) => {
        //   if (status === 'error') return;

          
        // })
      },

      /**
       * @desc 公交站点自动补全点击处理函数
       * @param station {Object} 公交站点信息
       */
      busStationClickHandler ({name, location, id: poiId}) {
        // 公交线路没有 location
        if (!location) {
          this.$router.go({
            name: 'bus-line',
            params: {
              lineName: name
              , cityCode: this.position.citycode
              , tripType: this.tripForm.tripType
              , stationType: this.tripForm.stationType
            }
          });
        }

        else {
          this.tripForm[`${this.tripForm.stationType}Name`] = name;
          this.tripForm[`${this.tripForm.stationType}Geo`] = { location: location.toString(), poiId };

          this.setStationInfo(this.tripForm);
          this.$router.go({
            name: 'setting-trip',
            params: {tripType: this.tripForm.type}
          })
        }
      },

      /**
       * @desc 搜索站点信息
       * @param keyword {String} 关键字
       */
      searchStation (keyword) {
        this.showNearlyStation = false;

        new Promise((resolve, reject) => {
          this.Autocomplete.search(keyword, (status, result) => {
            if (status === 'error' || status === 'on_data') reject(status, result);

            resolve(result);
          })
        }).then(({tips}) => {
          this.busStationAutoComplete = tips;
        }).catch((status, result) => {
          console.log(status, result);
        });
      },

      /**
       * @desc 附近站点公交线路点击处理函数
       * @param name {String} 站点线路名称
       * @param location {Object} 经纬度信息
       * @param type {String} busLine | busStation 用来区分是公交站还是公交线路
       * @param poiId {String} 高德公交站点 ID
       */
      nearlyPlaceClickHandler ({name, location, type, id: poiId}) {
        if (type === 'busLine') {
          this.$router.go({
            name: 'bus-line',
            params: {
              lineName: name
              , cityCode: this.position.citycode
              , tripType: this.tripForm.tripType
              , stationType: this.tripForm.stationType
            }
          });
        }

        else {
          this.tripForm[`${this.tripForm.stationType}Name`] = name;
          this.tripForm[`${this.tripForm.stationType}Geo`] = { location: location.toString(), poiId };

          this.setStationInfo(this.tripForm);
          this.$router.go({
            name: 'setting-trip',
            params: {tripType: this.tripForm.type}
          })
        }
      }
    },

    created () {
      debugger
      this.tripForm.tripType = this.$route.params.tripType;
      this.tripForm.stationType = this.$route.params.stationType;
    },

    components: { tab, tabs, toast }
  }
</script>

<style>
  /* 无框文本框文本域 */
.bd_none{border:0; outline:none;}
.PK-searchInput__wrap{
    padding: 3px 0;
    height: 34px;
    line-height: 34px;
    width: calc(100% - 0px);
    border-bottom: 1px solid #f1f1f1;
}
</style>


